import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hm_pda_app/components/top_header.dart';

// 盘点项目数据模型
class InventoryItem {
  final String id;
  final String itemCode;
  final String itemName;
  final int expectedQty;
  int actualQty;

  InventoryItem({
    required this.id,
    required this.itemCode,
    required this.itemName,
    required this.expectedQty,
    required this.actualQty,
  });

  // 计算差异
  int get difference => actualQty - expectedQty;

  // 是否有差异
  bool get hasDifference => difference != 0;
}

class InventoryCheck extends StatefulWidget {
  const InventoryCheck({super.key});

  @override
  State<InventoryCheck> createState() => _InventoryCheckState();
}

class _InventoryCheckState extends State<InventoryCheck> {
  final _formKey = GlobalKey<FormState>(); // 表单Key
  final GlobalKey<_InventoryCheckState> formKey =
      GlobalKey<_InventoryCheckState>();
  final _incomingGoodsController = TextEditingController();
  final _pickController = TextEditingController();
  final _focusNode = FocusNode();

  // 盘点数据列表
  final List<InventoryItem> _inventoryItems = [
    InventoryItem(
      id: '001',
      itemCode: 'SKU001SKU001SKU001SKU001',
      itemName: '铰链A型',
      expectedQty: 100,
      actualQty: 98,
    ),
    InventoryItem(
      id: '002',
      itemCode: 'SKU002',
      itemName: '螺丝B型',
      expectedQty: 500,
      actualQty: 500,
    ),
    InventoryItem(
      id: '003',
      itemCode: 'SKU003',
      itemName: '垫片C型',
      expectedQty: 200,
      actualQty: 205,
    ),
    InventoryItem(
      id: '004',
      itemCode: 'SKU004',
      itemName: '弹簧D型',
      expectedQty: 150,
      actualQty: 148,
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(title: const Text("移库")),
      appBar: const TopHeader(title: '盘点'),
      endDrawer: const CustomDrawer(),
      resizeToAvoidBottomInset: false,
      body: SingleChildScrollView(
        padding: EdgeInsets.all(1),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              // 收货单号
              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('盘点单号：', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _incomingGoodsController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _incomingGoodsController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _incomingGoodsController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _incomingGoodsController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          // getInfo(
                          //   incomingGoodsNo: _incomingGoodsController.text,
                          // );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              // 盘点详情
              Row(
                children: [
                  Expanded(
                    //  flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('盘点类型：仓库', isRequired: true),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              Row(
                children: [
                  Expanded(
                    // flex: 3,
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: _buildLabel('模式：静态盘点', isRequired: true),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: _buildLabel('库位：', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _incomingGoodsController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _incomingGoodsController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _incomingGoodsController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _incomingGoodsController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          // getInfo(
                          //   incomingGoodsNo: _incomingGoodsController.text,
                          // );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 3,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: _buildLabel('SkU编码', isRequired: true),
                    ),
                  ),
                  Expanded(
                    flex: 8,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: TextFormField(
                        controller: _incomingGoodsController,
                        decoration: _buildInputDecoration(
                          hintText: '',
                          controller: _incomingGoodsController,
                          suffixIcon: ValueListenableBuilder<TextEditingValue>(
                            valueListenable: _incomingGoodsController,
                            builder: (context, value, child) {
                              return value.text.isEmpty
                                  ? SizedBox.shrink()
                                  : IconButton(
                                      icon: Icon(Icons.clear, size: 20),
                                      onPressed: () {
                                        _incomingGoodsController.clear();
                                      },
                                    );
                            },
                          ),
                        ),
                        focusNode: _focusNode,
                        onFieldSubmitted: (value) {
                          //  _getInfoRequest();
                          // getInfo(
                          //   incomingGoodsNo: _incomingGoodsController.text,
                          // );
                          print('回车执行');
                        },
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),
              Row(
                children: [
                  Expanded(
                    flex: 1,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Image(
                        image: NetworkImage(
                          'https://hmdp.gzhimax.com:10001/hmdp/2025/10/17/c992aa12d6b4435696029cf7aafa4f0c.png',
                        ),
                        width: 100,
                        height: 100,
                      ),
                    ),
                  ),
                  Expanded(
                    flex: 4,
                    child: Align(
                      alignment: Alignment.centerLeft,
                      child: Column(
                        children: [
                          Row(
                            children: [
                              Expanded(
                                flex: 1,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: _buildLabel(
                                    '系统数量:100',
                                    isRequired: false,
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const Divider(
                            height: 2, // 容器总高度2像素
                            thickness: 1, // 分割线厚度5像素
                            indent: 0, // 左侧缩进20像素
                            endIndent: 0, // 右侧无缩进
                            color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                          ),
                          Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: Align(
                                  alignment: Alignment.centerLeft,
                                  child: _buildLabel('实盘数量', isRequired: true),
                                ),
                              ),
                              Expanded(
                                flex: 5,
                                child: TextFormField(
                                  keyboardType: TextInputType.number,
                                  controller: _pickController,

                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                  validator: (value) {
                                    if (value == null || value.isEmpty) {
                                      return '请输入数字';
                                    }
                                    if (int.tryParse(value) == null) {
                                      return '请输入有效的数字';
                                    }
                                    return null;
                                  },
                                  decoration: InputDecoration(
                                    contentPadding: EdgeInsets.symmetric(
                                      horizontal: 12,
                                      vertical: 8,
                                    ),
                                    // labelText: '数字输入',
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                      borderSide: BorderSide(
                                        color: Colors.grey[300]!,
                                      ),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(8),
                                      borderSide: BorderSide(
                                        color: Colors.grey[300]!,
                                      ),
                                    ),
                                    suffixIcon:
                                        ValueListenableBuilder<
                                          TextEditingValue
                                        >(
                                          valueListenable: _pickController,
                                          builder: (context, value, child) {
                                            return value.text.isEmpty
                                                ? SizedBox.shrink()
                                                : IconButton(
                                                    icon: Icon(
                                                      Icons.clear,
                                                      size: 20,
                                                    ),
                                                    onPressed: () {
                                                      _pickController.clear();
                                                    },
                                                  );
                                          },
                                        ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          const Divider(
                            height: 2, // 容器总高度2像素
                            thickness: 1, // 分割线厚度5像素
                            indent: 0, // 左侧缩进20像素
                            endIndent: 0, // 右侧无缩进
                            color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              const Divider(
                height: 2, // 容器总高度2像素
                thickness: 1, // 分割线厚度5像素
                indent: 0, // 左侧缩进20像素
                endIndent: 0, // 右侧无缩进
                color: Color.fromARGB(255, 109, 108, 108), // 黑色分割线
              ),

              // 添加列表展示区域
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: _buildList(),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: DecoratedBox(
        decoration: BoxDecoration(color: const Color.fromARGB(255, 77, 76, 76)),
        child: SizedBox(
          width: double.infinity,
          height: 50,
          child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              children: [
                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: OutlinedButton(
                      onPressed: () {
                        // 取消操作，重置表单
                        // _resetForm();
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._resetForm();
                      },
                      style: OutlinedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.grey[600],
                        side: BorderSide.none,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w500,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 1,
                      ),
                      child: const Text('清除'),
                    ),
                  ),
                ),
                const SizedBox(width: 12),

                Expanded(
                  child: SizedBox(
                    height: 40,
                    child: ElevatedButton(
                      onPressed: () {
                        // final formState = context
                        //     .findAncestorStateOfType<IncomingGoodsFormState>();
                        // formState?._submitForm();

                        showDialog(
                          context: context,
                          builder: (context) => AlertDialog(
                            title: Text('确认提交'),
                            content: Text('是否确认提交？'),
                            actions: [
                              TextButton(
                                onPressed: () =>
                                    Navigator.of(context).pop(false),
                                child: const Text('取消'),
                              ),
                              TextButton(
                                onPressed: () {
                                  // _submitForm();
                                  Navigator.of(context).pop(false);
                                },
                                child: const Text('确认'),
                              ),
                            ],
                          ),
                        );
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue[600],
                        foregroundColor: Colors.white,
                        textStyle: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 3,
                        // shadowColor: Colors.blue.withOpacity(0.3),
                      ),
                      child: const Text('提交'),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  // 列表展示
  Widget _buildList() {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      child: DataTable(
        columnSpacing: 20,
        columns: const [
          DataColumn(label: Text('盘点单号')),
          DataColumn(label: Text('盘点数量')),

          DataColumn(label: Text('操作')),
        ],
        rows: _inventoryItems.map((item) {
          return DataRow(
            cells: [
              DataCell(SizedBox(width: 120, child: Text('${item.itemCode}'))),

              DataCell(SizedBox(width: 60, child: Text('100'))),

              DataCell(
                SizedBox(
                  child: GestureDetector(
                    onTap: () {
                      // 删除操作
                    },
                    child: Text(
                      '选择',
                      style: TextStyle(
                        color: const Color.fromARGB(255, 74, 61, 187),
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
        }).toList(),
      ),
    );
  }

  // 重置表单
  void _resetForm() {
    _formKey.currentState!.reset();
    setState(() {
      _incomingGoodsController.clear();
      // 重置所有实际数量为预期数量
      for (var item in _inventoryItems) {
        item.actualQty = item.expectedQty;
      }
    });
  }

  // 提交表单
  void _submitForm() {
    if (!_formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('请检查表单中的错误'), duration: Duration(seconds: 1)),
      );
      return;
    }

    // 检查是否有差异项目
    final itemsWithDifference = _inventoryItems
        .where((item) => item.hasDifference)
        .toList();

    String message = '盘点完成！';
    if (itemsWithDifference.isNotEmpty) {
      message += '\n发现 ${itemsWithDifference.length} 项差异';
    }

    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(message), duration: Duration(seconds: 2)),
    );
  }
}

// 构建标签文本
Widget _buildLabel(String text, {bool isRequired = false}) {
  return SizedBox(
    // width: 200,
    child: Padding(
      padding: EdgeInsets.symmetric(horizontal: 2),
      child: Text(
        text,
        style: TextStyle(
          fontWeight: FontWeight.w500,
          fontSize: 16,
          color: isRequired ? Colors.red : Colors.grey[700],
        ),
      ),
    ),
  );
}

// 构建输入框装饰
InputDecoration _buildInputDecoration({
  required String hintText,
  required TextEditingController controller,
  Widget? suffixIcon,
}) {
  print('controller ${controller.text}');
  return InputDecoration(
    hintText: hintText,
    contentPadding: EdgeInsets.zero, // 设置上下左右内边距都为0
    // prefixIcon: Icon(prefixIcon, color: Colors.grey[600]),
    suffixIcon: suffixIcon,
    hintStyle: TextStyle(color: Colors.grey[500]),
    // isDense: true 属性用于减少输入框的垂直高度，使其更紧凑
    // 当设置为 true 时，会减少内边距，让输入框看起来更小更密集
    // 适用于需要节省空间或创建更紧凑布局的场景
    // isDense: true,
    filled: true,
    fillColor: Colors.grey[50],

    // suffixIcon: controller.text.isNotEmpty
    //             ? IconButton(
    //                 icon: Icon(Icons.clear, size: 20),
    //                 onPressed: () {
    //                   controller.clear();
    //                   // 需要通知父组件状态更新
    //                   if (mounted) {
    //                     setState(() {});
    //                   }
    //                 },
    //               )
    //             : null,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    enabledBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.grey[300]!),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.blue, width: 2),
    ),
    errorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red),
    ),
    focusedErrorBorder: OutlineInputBorder(
      borderRadius: BorderRadius.circular(8),
      borderSide: BorderSide(color: Colors.red, width: 2),
    ),
  );
}
